package com.kws.commercial.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kws.commercial.dao.CommercialContractTemplate;
import com.kws.commercial.dao.Info.QueryContractTemplatePageInfo;
import com.kws.commercial.dao.Rq.CreateContractTemplateRq;
import com.kws.commercial.dao.Rq.QueryContractTemplatePageRq;
import com.kws.commercial.dao.Rq.UpdateContractTemplateRq;
import com.kws.commercial.mapper.ContractTemplateMapper;
import com.kws.commercial.service.ContractTemplateService;
import com.kws.commercial.util.MinioAPI;
import com.kws.common.config.constant.MinioCommonBucket;
import com.kws.common.config.util.DateTimeUtil;
import com.kws.common.core.enums.ModelOpType;
import com.kws.common.core.exception.ServiceException;
import com.kws.common.core.sys.Ksys;
import com.kws.common.core.utils.KConstants;
import com.kws.common.security.utils.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.time.LocalDate;
import java.util.List;

/**
 * <b>ContractTemplateServiceImpl</b>
 *
 * @description: ContractTemplateServiceImpl <br>
 * @date: 2024/10/23 16:50 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class ContractTemplateServiceImpl extends ServiceImpl<ContractTemplateMapper, CommercialContractTemplate> implements ContractTemplateService {
    private static final Logger logger = LoggerFactory.getLogger(ContractTemplateServiceImpl.class);

    @Autowired
    private MinioAPI minioAPI;

    private final static String SLASH = "/";

    private final static String FILE_NAME_PREFIX_SEPARATOR = "-";

    @Value("${minio.ENDPOINT}")
    private String minioUrl;



    @Override
    public PageInfo<QueryContractTemplatePageInfo> queryContractTemplatePage(QueryContractTemplatePageRq rq) {
        if (null == rq.getPageNum() || 0 == rq.getPageNum()){
            rq.setPageNum(1);
        }
        if (null == rq.getPageSize() || 0 == rq.getPageSize()){
            rq.setPageSize(10);
        }
        PageHelper.startPage(rq.getPageNum(),rq.getPageSize());
        Long companyId = SecurityUtils.getCompanyId();
        List<QueryContractTemplatePageInfo> contractTemplatePageList = baseMapper.queryContractTemplatePage(rq.getContractTemplateName(),rq.getContractType(),companyId);
        PageInfo<QueryContractTemplatePageInfo> pageInfo = new PageInfo<>(contractTemplatePageList);
        return pageInfo;
    }

    @Override
    public boolean createContractTemplate(CreateContractTemplateRq rq) {
        CommercialContractTemplate commercialContractTemplate = new CommercialContractTemplate();
        commercialContractTemplate.setContractTemplateName(rq.getContractTemplateName());
        commercialContractTemplate.setContractType(rq.getContractType());
        commercialContractTemplate.setContractUrl(rq.getContractUrl());
        Ksys.setBasicModelData(commercialContractTemplate, SecurityUtils.getUserId().toString(), KConstants.DATA_ENABLE, ModelOpType.CREATE);
        int insert = baseMapper.insert(commercialContractTemplate);
        if (insert == 1){
            return true;
        }
        return false;
    }

    @Override
    public QueryContractTemplatePageInfo queryContractTemplateById(Long id) {
        return baseMapper.queryContractTemplateById(id);
    }

    @Override
    public boolean updateContractTemplate(UpdateContractTemplateRq rq) {
        CommercialContractTemplate commercialContractTemplate = baseMapper.selectById(rq.getId());
        if (null != commercialContractTemplate){
            commercialContractTemplate.setContractTemplateName(rq.getContractTemplateName());
            commercialContractTemplate.setContractType(rq.getContractType());
            commercialContractTemplate.setContractUrl(rq.getContractUrl());
            Ksys.setBasicModelData(commercialContractTemplate,SecurityUtils.getUserId().toString(),KConstants.DATA_ENABLE, ModelOpType.UPDATE);
            int i = baseMapper.updateById(commercialContractTemplate);
            if (i == 1){
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean deleteContractTemplateById(Long id) {
        CommercialContractTemplate commercialContractTemplate = baseMapper.selectById(id);
        if (null != commercialContractTemplate){
            commercialContractTemplate.setEnable("0");
            Ksys.setBasicModelData(commercialContractTemplate,SecurityUtils.getUserId().toString(),KConstants.DATA_DISABLE, ModelOpType.UPDATE);
            int i = baseMapper.updateById(commercialContractTemplate);
            if (i == 1){
                return true;
            }
        }
        return false;
    }

    @Override
    public String uploadContractTemplate(MultipartFile file) {
        try (InputStream is = file.getInputStream()) {
            String bucketName = MinioCommonBucket.HUATAI_PUB_BUCKET;
            String objectKey = getObjectKey(file.getSize(), file.getOriginalFilename());
            minioAPI.uploadInputStream(bucketName, objectKey, is, file.getContentType());
            logger.info("上传地址为:{}"+objectKey);
            return minioUrl+"/"+MinioCommonBucket.HUATAI_PUB_BUCKET+"/"+objectKey;
        } catch (Exception e) {
            logger.error("上传失败，", e);
            throw new ServiceException("上传失败，请重新上传");
        }
    }

    private String getObjectKey(Long fileSize,String fileName) {
        String date = DateTimeUtil.format(LocalDate.now(),"yyyyMMdd");

        StringBuilder objectKey = new StringBuilder(date);
        objectKey.append(SLASH).append(fileSize).append(FILE_NAME_PREFIX_SEPARATOR).append(fileName);
        return objectKey.toString();
    }
}
